package solution._0040._0043;

/**
 * Created by chen_snow
 * Date: 2021/5/29 23:55
 * Description:
 */
public class Solution {

    public static void main(String[] args) {
        multiply("123", "456");
    }

    public static String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }

        String result = "0";
        for (int i = 0; i < num1.length(); i++) {
            String temp = calculate(num2, num1.charAt(i), num1.length() - i - 1);
            result = result.length() >= temp.length() ? plus(result, temp) : plus(temp, result);
        }

        return result;
    }

    public static String calculate(String num, char ch, int index) {

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < index; i++) {
            stringBuilder.append(0);
        }

        int multiplier = ch - '0';

        int plus = 0;
        int remainder = 0;

        for (int i = num.length() - 1; i >= 0; i--) {
            int data = (num.charAt(i) - '0') * multiplier + plus;
            plus = data / 10;
            remainder = data - plus * 10;
            stringBuilder.append(remainder);
        }

        if (plus != 0) {
            stringBuilder.append(plus);
        }

        return stringBuilder.reverse().toString();
    }

    public static String plus(String num1, String num2) {
        StringBuilder stringBuilder = new StringBuilder();
        int plus = 0;
        int remainder = 0;

        int i = num1.length() - 1;
        for (int j = num2.length() - 1; j >= 0; j--, i--) {
            int data = (num1.charAt(i) - '0') + (num2.charAt(j) - '0') + plus;
            plus = data / 10;
            remainder = data - plus * 10;
            stringBuilder.append(remainder);
        }

        while (i >= 0) {
            int data = (num1.charAt(i) - '0') + plus;
            plus = data / 10;
            remainder = data - plus * 10;
            stringBuilder.append(remainder);
            i--;
        }

        if (plus != 0) {
            stringBuilder.append(plus);
        }

        return stringBuilder.reverse().toString();
    }
}
